<?php
/**
 * 匠言知识付费
 * Author: 山西匠言网络科技有限公司
 * This is not a free software, it under the license terms, you can visit https://www.zsffzxkc.cn/ get more details.
 */
namespace app\index\controller;
use think\Controller;
use think\File;
use think\Request;
use think\Seeeion;
use think\Db;
use org\Qiniu;
use org\Upayun;
use function Qiniu\base64_urlSafeEncode;
use org\AliOss;
use org\AliSts;

class
Upload extends Base
{

    /**
     * deleteImg 删除七牛图片文件
     * @return \think\response\
     */
    public function deleteImg(){
        $add = input('add');
        $up = new Qiniu();
        $res = $up->delFile($add,'');
        if($res){
            return json(['code'=>100,'msg'=>'删除失败！']);
        }else{
            return json(['code'=>200,'msg'=>'删除成功！']);
        }
    }


    /**
     * upload 上传图片&音频到七牛云
     *
     */
    public function upload(){
        $set=Db::name('storage')
            ->where('acid',1)
            ->find();
        $allowTypes =[
            'mp3',
            'ogg',
            'mp4',
            'webm',
            'jpg',
            'jpeg',
            'png',
            'gif',
            'pdf',
            'xls',
            'xlsx',
            'doc',
            'docx',
            'ppt',
            'pptx',
            'mp3',
            'mp4',
            'txt',
            'psd',
            'zip',
            'exe',
            'ttf',
            'bt',
            'flash',
            'html'
        ];
        $file = request()->file('file');
        $info  = $file->getInfo();
//        return json_encode($info);
        //取出图片后缀
        $type = explode(".",$info['name']);
        $type = end($type);
        if(!in_array($type,$allowTypes)){
            return '上传格式违法!';
        }
        if($set['upload_area'] == 1) {//七牛云
            $filePath = $_FILES['file']['tmp_name'];
            //取出图片后缀
            $type = explode(".",$_FILES['file']['name']);
            $type = end($type);
            $key = md5(time().uuid()).'.'.$type;
            $up = new Qiniu();
            $data = $up->uploadFile($filePath,$key);
            $config_qiniu = json_decode($set['qiniu'],true);
            echo $config_qiniu['domain'].$data;
            return;
        } elseif ($set['upload_area'] == 2) {//阿里云
            $filePath = $_FILES['file']['tmp_name'];
            //取出图片后缀
            $type = explode(".",$_FILES['file']['name']);
            $type = end($type);
            $key = md5(time().uuid()).'.'.$type;
            $config_ali = json_decode($set['ali'],true);
            $AliOss = new AliOss();
            $result = $AliOss->uploadFile($key, $filePath);
            //@unlink(ROOT_PATH . 'public' . DS . $filepath);
            if($result[0] == 0) {
                echo $config_ali['oss']['accessUrl'].$result[1];
                return;
            } else {
                $this->result(1,$result[1]);
            }
        } elseif ($set['upload_area'] == 0) {//本地
            $file = request()->file('file');
            $name = $file->getInfo('name');
            $arr = explode(".",$name);
            $type = end($arr);
            if($type == 'mp3') {
                $dir = ROOT_PATH . 'public' . DS . 'uploads/audios/';
                $bf_path = 'uploads/audios/';
            }elseif($type == 'mp4') {
                $dir = ROOT_PATH . 'public' . DS . 'uploads/videos/';
                $bf_path = 'uploads/videos/';
            }
            elseif($type == 'jpg' || $type == 'jpeg' || $type == 'png' || $type == 'gif') {
                $dir = ROOT_PATH . 'public' . DS . 'uploads/images/';
                $bf_path = 'uploads/images/';
            }
            if(!file_exists($dir)){
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                mkdir($dir, 0700,true);
            }
            $info = $file->move($dir);
            if($info){
                $newName = $info->getSaveName();
                $filepath= $bf_path.$newName;
                echo $filepath;
            }else{
                echo '上传失败';
            }
        }
    }

    /*
     * layui上传图片&音频
     */
    public function layUpload(){
        $set=Db::name('storage')
            ->where('acid',1)
            ->find();
        $allowTypes =[
            'mp3',
            'ogg',
            'mp4',
            'webm',
            'jpg',
            'jpeg',
            'png',
            'gif',
        ];
        $file = request()->file('file');
        $name = $file->getInfo('name');
        $arr = explode(".",$name);
        $type = end($arr);
        if(!in_array($type,$allowTypes)){
            return '上传格式违法!';
        }
        set_time_limit (0);
        $filePath = $_FILES['file']['tmp_name'];
        //取出图片后缀
        $type = explode(".",$_FILES['file']['name']);
        $type = end($type);
        //组装图片名
        $key = md5(time().uuid()).'.'.$type;
        $up = new Qiniu();
        $data = $up->uploadFile($filePath,$key);
        $config_qiniu = json_decode($set['qiniu'],true);
        return json(['code'=>0,'msg'=>'','data'=>['src'=>$config_qiniu['domain'].$data]]);
    }




    /*
     * wangEditor图片上传
     */
    public function wangUpload(){
        foreach($_FILES as $key=>$vo){
            $filePath = $vo['tmp_name'];
            //取出图片后缀
            $type = explode(".",$vo['name']);

            $type = end($type);
            $allowTypes =[
                'mp3',
                'ogg',
                'mp4',
                'webm',
                'jpg',
                'jpeg',
                'png',
                'gif',
            ];
            if(!in_array($type,$allowTypes)){
                return '上传格式违法!';
            }
            //组装图片名
            $key = md5(time().uuid()).'.'.$type;
            $up = new Qiniu();
            $name = $up->uploadFile($filePath,$key);
            $data[] = config('qiniu.domain').$name;
        }
        return json(['errno'=>0,'data'=>$data]);
    }


    /**
     * 百度富文本上传图片至第三方CDN接口
     * @throws \Exception
     */
    public function ueditorUpload(){
        $file = request()->file('upfile');
        $info  = $file->getInfo();
        //取出图片后缀
        $type = explode(".",$info['name']);
        $type = end($type);
        $allowTypes =[
            'mp3',
            'ogg',
            'mp4',
            'webm',
            'jpg',
            'jpeg',
            'png',
            'gif',
        ];
        if(!in_array($type,$allowTypes)){
            return '上传格式违法!';
        }
        //组装图片名
        $key = md5(time().uuid()).'.'.$type;

        $set=Db::name('storage')->field('upload_area')
            ->where('acid',1)
            ->find();
        if($set['upload_area'] == 1) {//七牛云
            $Qiniu = new Qiniu();
//            $arr = explode('.', $key);
//            $type = end($arr);
            $filepath = $Qiniu->uploadFile($info['tmp_name'],$key);
        } elseif ($set['upload_area'] == 2) {
            $AliOss = new AliOss();
            $result = $AliOss->uploadFile($key, $info['tmp_name']);
            if($result[0] == 0) {
                $filepath = $result[1];
            } else {
                $filepath = '';
                //$this->result(1,$result[1]);
            }
        } elseif ($set['upload_area'] == 3) {
            //腾讯云

        } else {
            //$file = request()->file('file');
            if($type == 'mp3') {
                $dir = '/uploads/audios/';
            } elseif($type == 'mp4') {
                $dir = '/uploads/video/';
            } else {
                $dir = '/uploads/images/';
            }
//            $dir = ROOT_PATH . 'public' . DS . 'uploads/images/';
            if(!file_exists(ROOT_PATH . 'public' . $dir)){
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                mkdir($dir, 0700,true);
            }
            $info1 = $file->move(ROOT_PATH . 'public' . $dir);
            if($info1) {
                $newName = $info1->getSaveName();
                $filepath = $dir . $newName;
            }
        }
        $url = to_media_url($filepath);
//        $up = new Qiniu();
//        $data = $up->uploadFile($info['tmp_name'],$key);
        //百度富文本上传文件到CDN upFile
        $res = array(
            "state"    => "SUCCESS",          //上传状态，上传成功时必须返回"SUCCESS"
            "url"      => $url,            //CDN地址
            "title"    => $key,          //新文件名
            "original" => $info['tmp_name'],       //原始文件名
            "type"     => ".".$type,           //文件类型
            "size"     => $info['size'],           //文件大小
        );
        echo json_encode($res);
    }

    /**
     * webupload Locality图片上传至本地&压缩
     */
    public function uploadLocality(){
        $file = request()->file('file');
        $info  = $file->getInfo();
        //取出图片后缀
        $type = explode(".",$info['name']);
        $type = end($type);
        $allowTypes =[
            'mp3',
            'ogg',
            'mp4',
            'webm',
            'jpg',
            'jpeg',
            'png',
            'gif',
            'pdf',
            'xls',
            'xlsx',
            'doc',
            'docx',
            'ppt',
            'pptx',
            'mp3',
            'mp4',
            'txt',
            'psd',
            'zip',
            'exe',
            'ttf',
            'bt',
            'flash',
            'html'
        ];
        if(!in_array($type,$allowTypes)){
            return '上传格式违法!';
        }
        $set=Db::name('storage')
            ->where('acid',1)
            ->find();
        if($set['upload_area'] == 1) {//七牛云
            $filePath = $_FILES['file']['tmp_name'];
            //取出图片后缀
            $type = explode(".",$_FILES['file']['name']);
            $type = end($type);
            $key = md5(time().uuid()).'.'.$type;
            $up = new Qiniu();
            $data = $up->uploadFile($filePath,$key);
            $config_qiniu = json_decode($set['qiniu'],true);
            echo $config_qiniu['domain'].$data;
            return;
        } elseif ($set['upload_area'] == 2) {//阿里云
            $filePath = $_FILES['file']['tmp_name'];
            //取出图片后缀
            $type = explode(".",$_FILES['file']['name']);
            $type = end($type);
            $key = md5(time().uuid()).'.'.$type;
            $config_ali = json_decode($set['ali'],true);
            $AliOss = new AliOss();
            $result = $AliOss->uploadFile($key, $filePath);
            //@unlink(ROOT_PATH . 'public' . DS . $filepath);
            if($result[0] == 0) {
                echo $config_ali['oss']['accessUrl'].$result[1];
                return;
            } else {
                $this->result(1,$result[1]);
            }
        } elseif ($set['upload_area'] == 0) {//本地
            $file = request()->file('file');
            $name = $file->getInfo('name');
            $arr = explode(".",$name);
            $type = end($arr);
            if($type == 'mp3') {
                $dir = ROOT_PATH . 'public' . DS . 'uploads/audios/';
                $bf_path = 'uploads/audios/';
            }elseif($type == 'mp4') {
                $dir = ROOT_PATH . 'public' . DS . 'uploads/videos/';
                $bf_path = 'uploads/videos/';
            }
            elseif($type == 'jpg' || $type == 'jpeg' || $type == 'png' || $type == 'gif') {
                $dir = ROOT_PATH . 'public' . DS . 'uploads/images/';
                $bf_path = 'uploads/images/';
            }
            if(!file_exists($dir)){
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                mkdir($dir, 0700,true);
            }
            $info = $file->move($dir);
            if($info){
                $newName = $info->getSaveName();
                $filepath= $bf_path.$newName;
                echo $filepath;
            }else{
                echo '上传失败';
            }
        }
    }
    /**
     * layui图片上传至本地&压缩
     */
    public function uploadLocal(){
        $file = request()->file('file');
        $info  = $file->getInfo();
        //取出图片后缀
        $type = explode(".",$info['name']);
        $type = end($type);
        $allowTypes =[
            'mp3',
            'ogg',
            'mp4',
            'webm',
            'jpg',
            'jpeg',
            'png',
            'gif',
        ];
        if(!in_array($type,$allowTypes)){
            return '上传格式违法!';
        }
        $dir = ROOT_PATH . 'public' . DS . 'uploads/images/';
        if(!file_exists($dir)){
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($dir, 0700,true);
        }
        $info = $file->move($dir);
        if($info){
            $newName = $info->getSaveName();
            //压缩图片
//            image_png_size_add(ROOT_PATH . 'public' . DS . 'uploads/images/'.$newName,ROOT_PATH . 'public' . DS . 'uploads/images/'.$newName);
            $filepath="/uploads/images/".$newName;
            //$set=$this->get_set('BASE');
            $set=Db::name('storage')->field('upload_area')
                ->where('acid',1)
                ->find();
            if($set['upload_area'] == 1) {//七牛云
                $Qiniu = new Qiniu();
                $arr = explode('.', $newName);
                $type = end($arr);
                $filepath_local = $filepath;
                $filepath = $Qiniu->uploadFile(ROOT_PATH . 'public' . $filepath, md5(time().uuid()).'.'.$type);
                unset($info);
                @unlink(ROOT_PATH . 'public' . $filepath_local);
            } elseif ($set['upload_area'] == 2) {
                $AliOss = new AliOss();
                $arr = explode('.', $newName);
                $type = end($arr);
                $result = $AliOss->uploadFile(md5(time().uuid()).'.'.$type, ROOT_PATH . 'public' . $filepath);
                unset($info);
                @unlink(ROOT_PATH . 'public' . $filepath);
                if($result[0] == 0) {
                    $filepath = $result[1];
                } else {
                    $this->result(1,$result[1]);
                }
            }
            $this->result(0,'上传成功',$filepath,0,'json');
        }else{
            $this->result(1,$file->getError());
        }
    }
    /**
     * deleteLocality 删除本地图片
     * @return \think\response\Json
     */
    public function deleteLocality(){
        $add  = input('add');
        $add = substr ($add,1);
        if(unlink($add)){
            return json(['code'=>200,'msg'=>'删除成功！']);
        }else{
            return json(['code'=>100,'msg'=>'删除失败！']);
        }
    }

    /*
     * video 视频文件上传到7牛（已废弃）
     */
    public function layUploadVideo(){
        $file = request()->file('file');
        $info  = $file->getInfo();
        //取出图片后缀
        $type = explode(".",$info['name']);
        $type = end($type);
        $allowTypes =[
            'mp3',
            'ogg',
            'mp4',
            'webm',
            'jpg',
            'jpeg',
            'png',
            'gif',
        ];
        if(!in_array($type,$allowTypes)){
            return '上传格式违法!';
        }
        set_time_limit (0);
        $filePath = $_FILES['file']['tmp_name'];
        //取出文件后缀
        $type = explode(".",$_FILES['file']['name']);
        $type = end($type);
        //组装文件名
        $key = md5(time().uuid()).'.'.$type;
        $up = new Qiniu();
        $data = $up->uploadVideo($filePath,$key);
        echo $data;
    }

    /**
     * video 视频文件上传至本地
     */
    public function video(){
        $file = request()->file('file');
        $info  = $file->getInfo();
        //取出图片后缀
        $type = explode(".",$info['name']);
        $type = end($type);
        $allowTypes =[
            'mp3',
            'ogg',
            'mp4',
            'webm',
            'jpg',
            'jpeg',
            'png',
            'gif',
        ];
        if(!in_array($type,$allowTypes)){
            return '上传格式违法!';
        }
        @set_time_limit(5 * 60);
        $targetDir = ROOT_PATH . 'public' . DS . 'uploads/video_tmp';
        $uploadDir = ROOT_PATH . 'public' . DS . 'uploads/video/'.date('Ymd');
        $cleanupTargetDir = true; // Remove old files
        $maxFileAge = 5 * 3600; // Temp file age in seconds
// Create target dir
        if (!file_exists($targetDir)) {
            @mkdir($targetDir,0700,true);
        }

// Create target dir
        if (!file_exists($uploadDir)) {
            @mkdir($uploadDir,0700,true);
        }

// Get a file name
        if (!empty($_FILES)) {
            $fileName = $_FILES["file"]["name"];
        } else {
            $fileName = uniqid("file_");
        }

        $filePath = $targetDir . DS . iconv("UTF-8","gb2312",$fileName);
//        $uploadPath = $uploadDir . DS . iconv("UTF-8","gb2312",$fileName);

// Chunking might be enabled
        $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
        $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 1;

// Remove old temp files
        if ($cleanupTargetDir) {
            if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
            }

            while (($file = readdir($dir)) !== false) {
                $tmpfilePath = $targetDir . DS . $file;

                // If temp file is current file proceed to the next
                if ($tmpfilePath == "{$filePath}_{$chunk}.part" || $tmpfilePath == "{$filePath}_{$chunk}.parttmp") {
                    continue;
                }

                // Remove temp file if it is older than the max age and is not the current file
                if (preg_match('/\.(part|parttmp)$/', $file) && (@filemtime($tmpfilePath) < time() - $maxFileAge)) {
                    @unlink($tmpfilePath);
                }
            }
            closedir($dir);
        }


// Open temp file
        if (!$out = @fopen("{$filePath}_{$chunk}.parttmp", "wb")) {
            die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
        }

        if (!empty($_FILES)) {
            if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
            }
            // Read binary input stream and append it to temp file
            if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        } else {
            if (!$in = @fopen("php://input", "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        }
        while ($buff = fread($in, 4096)) {
            fwrite($out, $buff);
        }
        @fclose($out);
        @fclose($in);
        rename("{$filePath}_{$chunk}.parttmp", "{$filePath}_{$chunk}.part");
        $index = 0;
        $done = true;
        for( $index = 0; $index < $chunks; $index++ ) {
            if ( !file_exists("{$filePath}_{$index}.part") ) {
                $done = false;
                break;
            }
        }
        if ( $done ) {
            $name = uuid();
//            if (!file_exists($uploadDir . DS . $name)) {
                @mkdir($uploadDir . DS . $name,0700,true);
//            }
            $uploadPath = $uploadDir . DS . $name . DS . iconv("UTF-8","gb2312",$fileName);
            if (!$out = @fopen($uploadPath, "wb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
            }

            if ( flock($out, LOCK_EX) ) {
                for( $index = 0; $index < $chunks; $index++ ) {
                    if (!$in = @fopen("{$filePath}_{$index}.part", "rb")) {
                        break;
                    }

                    while ($buff = fread($in, 4096)) {
                        fwrite($out, $buff);
                    }

                    @fclose($in);
                    @unlink("{$filePath}_{$index}.part");
                }

                flock($out, LOCK_UN);
            }
            @fclose($out);
            echo 'uploads/video/'.date('Ymd'). '/' .$name. '/' .$fileName;
        }
    }

    /**
     * video 视频文件上传至本地
     */
    public function video1(){
        $file = request()->file('file');
        $info  = $file->getInfo();
        //取出图片后缀
        $type = explode(".",$info['name']);
        $type = end($type);
        $allowTypes =[
            'mp3',
            'ogg',
            'mp4',
            'webm',
            'jpg',
            'jpeg',
            'png',
            'gif',
        ];
        if(!in_array($type,$allowTypes)){
            return '上传格式违法!';
        }
        @set_time_limit(5 * 60);
        $targetDir = ROOT_PATH . 'public' . DS . 'uploads/video_tmp';
        $uploadDir = ROOT_PATH . 'public' . DS . 'uploads/video/'.date('Ymd');
        $cleanupTargetDir = true; // Remove old files
        $maxFileAge = 5 * 3600; // Temp file age in seconds
// Create target dir
        if (!file_exists($targetDir)) {
            @mkdir($targetDir,0700,true);
        }

// Create target dir
        if (!file_exists($uploadDir)) {
            @mkdir($uploadDir,0700,true);
        }

// Get a file name
        if (!empty($_FILES)) {
            $fileName = $_FILES["file"]["name"];
        } else {
            $fileName = uniqid("file_");
        }
        $arr = explode('.', $fileName);
        $ext = end($arr);

        $filePath = $targetDir . DS . iconv("UTF-8","gb2312",$fileName);
//        $uploadPath = $uploadDir . DS . iconv("UTF-8","gb2312",$fileName);

// Chunking might be enabled
        $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
        $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 1;

// Remove old temp files
        if ($cleanupTargetDir) {
            if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
            }

            while (($file = readdir($dir)) !== false) {
                $tmpfilePath = $targetDir . DS . $file;

                // If temp file is current file proceed to the next
                if ($tmpfilePath == "{$filePath}_{$chunk}.part" || $tmpfilePath == "{$filePath}_{$chunk}.parttmp") {
                    continue;
                }

                // Remove temp file if it is older than the max age and is not the current file
                if (preg_match('/\.(part|parttmp)$/', $file) && (@filemtime($tmpfilePath) < time() - $maxFileAge)) {
                    @unlink($tmpfilePath);
                }
            }
            closedir($dir);
        }


// Open temp file
        if (!$out = @fopen("{$filePath}_{$chunk}.parttmp", "wb")) {
            die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
        }

        if (!empty($_FILES)) {
            if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
            }
            // Read binary input stream and append it to temp file
            if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        } else {
            if (!$in = @fopen("php://input", "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        }
        while ($buff = fread($in, 4096)) {
            fwrite($out, $buff);
        }
        @fclose($out);
        @fclose($in);
        rename("{$filePath}_{$chunk}.parttmp", "{$filePath}_{$chunk}.part");
        $index = 0;
        $done = true;
        for( $index = 0; $index < $chunks; $index++ ) {
            if ( !file_exists("{$filePath}_{$index}.part") ) {
                $done = false;
                break;
            }
        }
        if ( $done ) {
            $name = uuid();
//            if (!file_exists($uploadDir . DS . $name)) {
            @mkdir($uploadDir . DS . $name,0700,true);
//            }
            $uploadPath = $uploadDir . DS . $name . DS . iconv("UTF-8","gb2312",$fileName);
            if (!$out = @fopen($uploadPath, "wb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
            }

            if ( flock($out, LOCK_EX) ) {
                for( $index = 0; $index < $chunks; $index++ ) {
                    if (!$in = @fopen("{$filePath}_{$index}.part", "rb")) {
                        break;
                    }

                    while ($buff = fread($in, 4096)) {
                        fwrite($out, $buff);
                    }

                    @fclose($in);
                    @unlink("{$filePath}_{$index}.part");
                }

                flock($out, LOCK_UN);
            }
            @fclose($out);
            echo 'uploads/video/'.date('Ymd'). '/' .$name. '/' .$fileName;
        }
    }

    //后台用户修改头像上传
    public function updateFace(){

        $base64url = input('base64url');
        $arr = base64_img($base64url,true);
        if($arr['code'] == 200){
            $res = Db::name('admin')->where('id',input('id'))->update(["portrait"=>$arr['msg']]);
            if($res){
                session('portrait', $arr['msg']); //用户头像
                return json(['code'=>200,'msg'=>"上传成功"]);
            }else{
                return json(['code'=>100,'msg'=>"上传失败"]);
            }
        }elseif($arr['code'] == 100){
            writelog('管理员上传头像失败',100);
            return json($arr);
        }
    }

    //多图修改测试页面
    public function showImg(){
        $photo = Db::name('img')->where('id',1)->value('img');
        $arr = explode(',',$photo);
        $this->assign ('photo',$photo);
        $this->assign ('arr',$arr);
        return $this->fetch('/webuploader2');
    }
    //七牛云文件上传测试
    public function qiNuiUpload(){
        // 持久化存储凭证
        //持久化数据处理的上传凭证

        $saveMp4Entry = base64_urlSafeEncode($bucket . ":avthumb_test_target.mp4");
        $avthumbMp4Fop = "avthumb/mp4|saveas/" . $saveMp4Entry;
        $vframeJpgFop = "vframe/jpg/offset/1|saveas/" . $saveJpgEntry;
        $policy = array(
            'persistentOps' => $avthumbMp4Fop . ";" . $vframeJpgFop,
            'persistentPipeline' => "video-pipe",
            'persistentNotifyUrl' => "http://api.example.com/qiniu/pfop/notify",
        );
        $upToken = $auth->uploadToken($bucket, null, $expires, $policy, true);
        print($upToken . "\n");
    }
    //最新视频分片上传到7牛
    public function uptoken(){
        $fileName = input('get.fileName');
        $fileName_arr = explode('.',$fileName);
        $type = end($fileName_arr);
        //组装文件名
        $key = md5(time().uuid()).'.'.$type;
        $set=Db::name('storage')->where('acid',1)->find();
        //$set=$this->get_set('BASE');
        if($set['upload_area'] == 1) {//七牛云
            return json(['uptoken' => (new Qiniu())->upTokenByM3u8($fileName),'key'=>$key]);
        } elseif($set['upload_area'] == 2) {//aliyun
            //使用 总后台accessid key
//            $alists = new AliSts();
//            $result = $alists->getSts();
//            $result['key'] = $key;
            if(1 || $result[0] == 0) {
                $config = json_decode($set['ali'], true);
                $result = $config;
                $result['bucket'] = $config['oss']['bucket'];
                $result['key'] = $key;
                $result['accessUrl'] = $config['oss']['accessUrl'].$key;
            }
            return json($result);
        }
    }

    /**
     * 转码
    */
    public function persistentFops(){
        $post = input();
        $filename = $post['filename'];
        $set=Db::name('storage')->where('acid',1)->find();
        if($set['upload_area'] == 1) {//七牛云
            $qiniu = new Qiniu();
            $qiniu_set = json_decode($set['qiniu'], true);
            $qiniu_set['totype'] = 'm3u8';
            $qiniu_set['use_watermark'] = $set['use_watermark'];
            $qiniu_set['watermark_type'] = $set['watermark_type'];
            $qiniu_set['watermark_text'] = $set['watermark_text'];
            $qiniu_set['watermark_image_addr'] = $set['watermark_image_addr'];
            //$qiniu_set['watermark_location'] = $set['watermark_location'];
            //$qiniu_set['watermark_location'] = $qiniu_set['watermark_location'];
//            if(!empty($qiniu_set['watermark_image_addr'])) {
//                $qiniu_set['watermark_image_addr'] = $qiniu_set['domain'].$qiniu_set['watermark_image_addr'];
//            }
            $fopid = $qiniu->PersistentFop($filename, $qiniu_set);
            return json($fopid);
        } elseif($set['upload_area'] == 2) {//aliyun
            $post = input();
            $file = explode('/',$post['filename']);
            //$filename = 'https://jyzsff.oss-cn-hangzhou.aliyuncs.com/0d7ab2bdc7d9b4edcf464f371b4d8e2e.mp4';
            $filename = $file[count($file)-1];
            $Outputsname = explode('.',$filename);
            $storage_config=Db::name('storage')
                ->where('acid',1)
                ->field('ali,watermark_image_addr')
                ->find();
            $config = json_decode($storage_config['ali'], true);

            //水印模板id
            $watermarktemplate = $this->addWaterMarkTemplate();
            //转码模板id
            $templateresponse = $this->addTemplateResponse();
            //获取水印图片
            $watermarkimg = explode('/',$storage_config['watermark_image_addr']);
            $watermarkimgname = $watermarkimg[count($watermarkimg)-1];

            $arr['Bucket'] = $config['oss']['bucket'];
            $arr['Location'] = "oss-cn-hangzhou";
            $arr['Object'] = $filename;
            $OutputBucket = $config['oss']['bucket'];
            $Outputs['OutputObject'] = $Outputsname[0];
            $Outputs['TemplateId'] = $templateresponse;
            $Outputs['WaterMarks'] = [array(
                'InputFile' => array(
                    'Bucket' => $config['oss']['bucket'],
                    'Location' => 'oss-cn-hangzhou',
                    'Object' => $watermarkimgname
                ),
                'WaterMarkTemplateId' => $watermarktemplate
            )];
            $Outputs['UserData'] = 'testid-001';
            //return json([json_encode($Outputs)]);die;

            $Outputs2 = array($Outputs);
            //管道id
            $PipelineId = $this->searchPipeline();
            $alists = new AliSts();
            $result = $alists->submitJobM3u8(json_encode($arr),$PipelineId,$OutputBucket,json_encode($Outputs2));
            return json($result);
        }
    }

    //测试阿里云转码接口
    public function ceali(){
        $post = input();
        $file = explode('/',$post['str']);
        $filename = $file[count($file)-1];
        $Outputsname = explode('.',$filename);
        $storage_config=Db::name('storage')
            ->where('acid',1)
            ->field('ali,watermark_image_addr')
            ->find();
        $config = json_decode($storage_config['ali'], true);

        //获取水印图片
        $watermarkimg = explode('/',$storage_config['watermark_image_addr']);
        $watermarkimgname = $watermarkimg[count($watermarkimg)-1];

        //水印模板id
        $watermarktemplate = $this->addWaterMarkTemplate();
        //转码模板id
        $templateresponse = $this->addTemplateResponse();

        $arr['Bucket'] = $config['oss']['bucket'];
        $arr['Location'] = "oss-cn-hangzhou";
        $arr['Object'] = $filename;
        $OutputBucket = $config['oss']['bucket'];
        $Outputs['OutputObject'] = $Outputsname[0];
        $Outputs['TemplateId'] = $templateresponse;
        $Outputs['WaterMarks'] = [array(
            'InputFile' => array(
                'Bucket' => $config['oss']['bucket'],
                'Location' => 'oss-cn-hangzhou',
                'Object' => $watermarkimgname
            ),
            'WaterMarkTemplateId' => $watermarktemplate
        )];
        $Outputs['UserData'] = 'testid-001';
        //return json([json_encode($Outputs)]);die;

        $Outputs2 = array($Outputs);
        //管道id
        $PipelineId = $this->searchPipeline();
        $alists = new AliSts();
        $result = $alists->submitJobM3u8(json_encode($arr),$PipelineId,$OutputBucket,json_encode($Outputs2));
        return json($result);
    }

    /*
     * 获取管道id(搜索管道)
     * */
    public function searchPipeline(){

        $storage_config=Db::name('storage')
            ->where('acid',1)
            ->field('ali,watermark_image_addr')
            ->find();
        $config = json_decode($storage_config['ali'], true);

        if(isset($config['PipelineId'])){
            $PipelineId = $config['PipelineId'];
        }else{
            $alists = new AliSts();
            $result = $alists->searchPipeline();
            if($result[0] == 0){
                $PipelineId = $result[1]['PipelineList']['Pipeline'][0]['Id'];

                $config['PipelineId'] = $PipelineId;

                $res=Db::name('storage')
                    ->where('acid',1)
                    ->update(['ali'=>json_encode($config)]);

            }else{
                return json($result);
            }
        }

        return $PipelineId;
    }

    /*
     * 创建水印模板
     * */
    public function addWaterMarkTemplate(){
        $storage_config=Db::name('storage')
            ->where('acid',1)
            ->field('ali,watermark_image_addr')
            ->find();
        $config = json_decode($storage_config['ali'], true);

        if(isset($config['watermarktemplate'])){
            $watermarktemplate = $config['watermarktemplate'];
        }else{
            $name = 'ceshi';
            $templateconfig = array(
                'Dx'=>'10',
                'Dy'=>'5',
                'ReferPos'=>$config['watermark_location'],
                'Type'=>'Image',
                'Timeline'=>array(
                    'Start'=>'0',
                    'Duration'=>'10'
                )
            );
            $alists = new AliSts();
            $result = $alists->waterMarkTemplate($name,json_encode($templateconfig));
            if($result[0] == 0){
                $watermarktemplate = $result[1]['WaterMarkTemplate']['Id'];

                $config['watermarktemplate'] = $watermarktemplate;

                $res=Db::name('storage')
                    ->where('acid',1)
                    ->update(['ali'=>json_encode($config)]);

            }else{
                return json($result);
            }
        }

        return $watermarktemplate;
    }

    /*
     * 创建自定义转码模板
     * */
    public function addTemplateResponse(){
        $storage_config=Db::name('storage')
            ->where('acid',1)
            ->field('ali,watermark_image_addr')
            ->find();
        $config = json_decode($storage_config['ali'], true);

        if(isset($config['templateresponse'])){
            $templateresponse = $config['templateresponse'];
        }else{
            $name = 'ceshi';
            $templateconfig = array(
                'Format'=>'m3u8'
            );
            $Video = array(
              'Codec'=>'H.264',
            );
            $alists = new AliSts();
            $result = $alists->templateResponse($name,json_encode($templateconfig),json_encode($Video));
            if($result[0] == 0){
                $templateresponse = $result[1]['Template']['Id'];

                $config['templateresponse'] = $templateresponse;

                $res=Db::name('storage')
                    ->where('acid',1)
                    ->update(['ali'=>json_encode($config)]);

            }else{
                return json($result);
            }
        }

        return $templateresponse;
    }


    /*查询转码是否成功*/
    public function queryPersistentFopStatus(){
        $set=Db::name('storage')->where('acid',1)->find();
        $id = input('id');
        if($set['upload_area'] == 1) {//七牛云
            $config = json_decode($set['qiniu'], true);
            $qiniu = new Qiniu();
            $res = $qiniu->queryPersistentFopStatus($id);
            $res['url'] = $config['domain'];
            return json($res);
        } elseif($set['upload_area'] == 2) {//aliyun
            $config = json_decode($set['ali'], true);
            $alists = new AliSts();
            $res = $alists->queryJobList($id);
            $res['url'] = $config['oss']['accessUrl'];
            return json($res);
        }
    }

}